package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * 动态评论-点赞、喜欢、评论
 */
@Service
@Slf4j
public class CommentApiImpl implements CommentApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 动态操作-点赞、喜欢、评论
     * @param comment
     * @return
     */
    @Override
    public Long save(Comment comment) {
        //a.获取当前用户id 发布表动态id 保存评论记录（点赞记录）
        comment.setId(ObjectId.get());//主键id
        comment.setCreated(System.currentTimeMillis());//当前时间
        if(comment.getPubType() == 1 ){//对动态的操作
            //根据发布表主键id 查询动态对象 得到发布表用户id
            Publish publish = mongoTemplate.findById(comment.getPublishId(), Publish.class);
            comment.setPublishUserId(publish.getUserId());//被评论人用户id
        }
        mongoTemplate.save(comment);
        //b.修改发布表点赞数量+1  条件： publishId 更新 发布表 点赞数+1
        updateCount(comment,1);
        //c.查询点赞数量 查询发布表点赞数
        Long total = getCount(comment);
        return total;
    }

    /**
     * 获取点赞或取消点赞后 数量
     * @param comment
     * @return
     */
    private Long getCount(Comment comment) {
        Query query = new Query(Criteria.where("id").is(comment.getPublishId()));
        if(comment.getPubType() == 3){
            Comment countComment = mongoTemplate.findOne(query, Comment.class);
            log.debug("Comment hehe 应该正确了"+countComment.toString());
            return countComment.getLikeCount().longValue();
        }
        if(comment.getPubType() == 1) {
            //仅仅针对动态操作
            Publish publish = mongoTemplate.findOne(query,  Publish.class);
            log.debug("Publish hehe 应该正确了"+publish.toString());
            if (comment.getCommentType() == 1) {  //评论类型，1-点赞，2-评论，3-喜欢
                return publish.getLikeCount().longValue();
            }
            if (comment.getCommentType() == 2) {  //评论类型，1-点赞，2-评论，3-喜欢
                return publish.getCommentCount().longValue();
            }
            if (comment.getCommentType() == 3) {  //评论类型，1-点赞，2-评论，3-喜欢
                return publish.getLoveCount().longValue();
            }
        }
        log.debug("hehe 我错了。。。");
        return 0l;
    }

    /**
     * 更新数量+1 或 -1
     * @param comment
     * @param count
     */
    private void updateCount(Comment comment, int count) {
        //根据发布id查询发布表记录 更新点赞数+1
        Query query = new Query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        update.inc(comment.getCol(),count);
        Class<?> myClass = Publish.class;//默认对动态表操作更新
        if(comment.getPubType() == 3){
            myClass = Comment.class;
        }
        mongoTemplate.updateFirst(query,update,myClass);
        log.debug("updateCount hehe 应该正确了"+comment.getPublishId()+"***"+comment.getCol()+"***"+count);
    }

    /**
     * 点赞、喜欢取消
     * @param comment
     * @return
     */
    @Override
    public Long remove(Comment comment) {
        //a.获取当前用户id 发布表动态id 删除评论记录（点赞记录）
        Query query = new Query(Criteria.where("userId").is(comment.getUserId())
        .and("commentType").is(comment.getCommentType())
        .and("publishId").is(comment.getPublishId()));//发布id 或 评论id
        mongoTemplate.remove(query,Comment.class);
        //b.修改发布表点赞数量+1  条件： publishId commentType pubType userId
        updateCount(comment,-1);
        //c.查询点赞数量
        Long total = getCount(comment);
        return total;
    }

    /**
     * 评论列表
     * movementId:发布id
     */
    @Override
    public PageResult<Comment> queryCommentListByPage(Comment comment, int page, int pagesize) {
        //1.总记录数
        Query query = new Query(Criteria.where("publishId").is(comment.getPublishId())
        .and("commentType").is(2)
        .and("pubType").is(1));
        long counts = mongoTemplate.count(query, Comment.class);
        //2.根据条件分页查询评论列表
        //query.skip(page-1).limit(pagesize);
        PageRequest pageRequest = PageRequest.of(page-1,pagesize);
        query.with(pageRequest);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        //3.封装返回PageResult
        long pages = counts/pagesize + counts%pagesize > 0 ? 1:0;
        return new PageResult<Comment>(counts,(long)pagesize,pages,(long)page,commentList);
    }

    /**
     * 喜欢列表 点赞列表 评论列表
     * //评论类型，1-点赞，2-评论，3-喜欢
     * @param page
     * @param pagesize
     * @param type
     * @return
     */
    @Override
    public PageResult<Comment> messageCommentList(Integer page, Integer pagesize, int type, Long userId) {
        //1.总记录数
        Query query = new Query(Criteria.where("commentType").is(type)
                .and("publishUserId").is(userId));
        long counts = mongoTemplate.count(query, Comment.class);
        //2.根据条件分页查询评论列表
        //query.skip(page-1).limit(pagesize);
        PageRequest pageRequest = PageRequest.of(page-1,pagesize);
        query.with(pageRequest);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        //3.封装返回PageResult
        long pages = counts/pagesize + counts%pagesize > 0 ? 1:0;
        return new PageResult<Comment>(counts,(long)pagesize,pages,(long)page,commentList);
    }
}
